<?php

namespace App\Lib;


use Gouguoyin\EasyHttp\Http;

class Kuaidi100
{

    public static function handle(array $array): array
    {
        if (!isset($array['com']) || empty($array['com'])) {
            throw new \Exception('快递公司编号不能为空');
        }
        if (!isset($array['num']) || empty($array['num'])) {
            throw new \Exception('快递单号不能为空');
        }
        if (!isset($array['phone']) || empty($array['phone'])) {
            $array['phone'] = '';
        } else {
            $array['phone'] = substr($array['phone'], -4);
        }
        return self::getInfo($array['com'], $array['num'], $array['phone']);
    }

    /**
     * @desc   getCookie
     * @return string
     */
    protected static function getCookie()
    {
        $cookie = 'Hm_lvt_=1;';
        $header = get_headers('https://www.kuaidi100.com/', true);
        if (isset($header['Set-Cookie'])) {
            $cookieStr = implode(';', $header['Set-Cookie']);
            $cookieArr = explode(';', $cookieStr);
            foreach ($cookieArr as $item) {
                $tmpArr = explode('=', $item);
                if (isset($tmpArr['0']) && in_array($tmpArr['0'], ['csrftoken', 'WWWID'])) {
                    $cookie .= trim($item) . ';';
                }
            }
        }
        return $cookie;
    }

    /**
     * @desc   getInfo
     * @param  string $com
     * @param  string $num
     * @param  string $phone
     * @return array
     */
    protected static function getInfo(string $com, string $num, $phone = ''): array
    {
        $urlTpl = 'https://www.kuaidi100.com/query?type=%s&postid=%s&temp=0.0099899%s&phone=%s';
        $urlStr = sprintf($urlTpl, $com, $num, time(), $phone);
        $header = [
            'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36',
            'Referer' => 'https://www.kuaidi100.com/',
            'Cookie' => self::getCookie()
        ];
        $body = Http::withHeaders($header)->asJson()->get($urlStr)->json();
        dd($body);
    }
}


